package com.pdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.pdp.dto.Result;
import com.pdp.entity.ShopType;
import com.pdp.mapper.ShopTypeMapper;
import com.pdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dabidai
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //从Redis查询店铺类型
        String shoptype = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE);

        // Redis中是否存在shoptype
        if(StrUtil.isNotBlank(shoptype)){
            // 存在，直接返回
            List<ShopType> list = JSONUtil.toList(shoptype, ShopType.class);
            return Result.ok(list);
        }

        // 不存在，从数据库查找
        List<ShopType> list = query().orderByAsc("sort").list();

        // 不存在，报错
        if(list == null){
            return Result.fail("店铺类型不存在");
        }

        // 存在，存入Redis中
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE, JSONUtil.toJsonStr(list));

        return Result.ok(list);
    }
}
